package um.android;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.util.Log;

public class SessionService extends Service {
	private static final String TAG = "SessionService";
	private static BroadcastReceiver SServiceInsc;
	private static BroadcastReceiver SServiceSender;
	BufferedReader in = null, in2=null, in3=null;
	HttpClient client = new DefaultHttpClient(); //Session Handler (Mantiene la conexión auntenticada)
	
	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
	
	@Override
	public void onCreate() {
     

		Log.d("CreateService", "onCreate");
		
		IntentFilter filter1 = new IntentFilter();
        filter1.addAction("um.android.requestlib");
        
        IntentFilter filter2 = new IntentFilter();
        filter2.addAction("um.android.requestinsc");
	    
	     SServiceSender = new BroadcastReceiver() {

    	    @Override
    	    public void onReceive(Context context, Intent intent) {
    	    	HttpGet request = new HttpGet("http://www.um.edu.ar/fi/estado.php");
    	    	try {
					HttpResponse response = client.execute(request);
					
					
					in = new BufferedReader
		            (new InputStreamReader(response.getEntity().getContent()));
		            StringBuffer sb = new StringBuffer("");
		            String line = "";
		            String NL = System.getProperty("line.separator");
		            while ((line = in.readLine()) != null) {
		                sb.append(line + NL);
		            }
		            in.close();
		            String carreras = sb.toString().substring(sb.toString().indexOf("<select"), sb.toString().indexOf("</select>"));
					
		            // Por ahora por defecto traemos la 1er carrera que aparezca.
		            
		            carreras = carreras.substring(carreras.indexOf("</option>"));
		            String label = carreras.substring(carreras.indexOf("label="),carreras.indexOf(" value"));
		            label= label.substring(7, label.length()-1);
		            
		            int offset = carreras.indexOf("value=") + 7;
		            String value = carreras.substring(offset,offset+3);
		            

		            Log.d("label", label);
		            Log.d("value",value);
		            
		            //Traemos la libreta:
		            
		            HttpPost request2 = new HttpPost("http://www.um.edu.ar/fi/estadoAcademico.php");
		            
			        List<NameValuePair>  nameValuePairs = new ArrayList<NameValuePair>(1);
			        nameValuePairs.add(new BasicNameValuePair("carrera",value));
			        
			        request2.setEntity(new UrlEncodedFormEntity( nameValuePairs));
			       
		 
			        HttpResponse response2 = client.execute(request2);
			        
			        Log.d("libreta", response2.toString());
			       
			        //Parceamos
			        in2 = new BufferedReader
		            (new InputStreamReader(response2.getEntity().getContent()));
		            StringBuffer sb2 = new StringBuffer("");
		            String line2 = "";
		            String NL2 = System.getProperty("line.separator");
		            while ((line2 = in2.readLine()) != null) {
		                sb2.append(line2 + NL2);
		            }
		            in2.close();
		            String libreta= sb2.toString().substring(sb2.toString().indexOf("<td>1"),sb2.toString().indexOf("</tbody>"));
		            
		            
		            //La mandamos al broadcast
		            Intent lib = new Intent();
			        lib.setAction("um.android.libreta");
			        lib.putExtra("libreta",libreta);
			        sendBroadcast(lib);
			        
		            
				} catch (ClientProtocolException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}	
    	    }
	    };
  	
  	
  	
  	

  	SServiceInsc = new BroadcastReceiver() {

	    @Override
	    public void onReceive(Context context, Intent intent) {
	    	//Para saltarnos el site de notificaciones de pago etc...
	    	HttpGet requestSkip = new HttpGet("http://www.um.edu.ar/fi/anuncio2.php");
	    	try {
				client.execute(requestSkip);
	    	
	    } catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
			//ahora sí traemos la pagina de inscripciones:
	    	HttpGet request = new HttpGet("http://www.um.edu.ar/fi/inscripcion.php");
	    	try {
				HttpResponse response = client.execute(request);
				
				in3 = new BufferedReader
	            (new InputStreamReader(response.getEntity().getContent()));
	            StringBuffer sb = new StringBuffer("");
	            String line = "";
	            String NL = System.getProperty("line.separator");
	            while ((line = in3.readLine()) != null) {
	                sb.append(line + NL);
	            }
	            in3.close();
	            
	            String inscrip= sb.toString();
	            if(intent.getExtras().getString("getinsc").equalsIgnoreCase("0")) { //Inscripción
	            	
	            	String data1= inscrip.substring(inscrip.toString().indexOf("Carrera"),inscrip.toString().indexOf("Opciones"));
	            	Log.d("INSCRIPCION", data1);
	            }
	            else { //Desinscripción
	            	String data2= inscrip.substring(inscrip.toString().indexOf("Materias inscriptas"));
	            	String data3= data2.substring(data2.toString().indexOf("<select"),data2.toString().indexOf("</select>"));
	            	Log.d("DESINCRIP", data3);
	            	
	            	 //La mandamos al broadcast
		            Intent lib = new Intent();
			        lib.setAction("um.android.desinsc");
			        lib.putExtra("data",data3);
			        sendBroadcast(lib);
	            }
				
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	    }
  	};
  	
  	registerReceiver(SServiceSender, filter1);
  	registerReceiver(SServiceInsc, filter2);
	
}

	
	@Override
	public void onDestroy() {
		super.onDestroy();
		unregisterReceiver(SServiceSender);
		unregisterReceiver(SServiceInsc);
	}
	
	@Override
	public void onStart(Intent intent, int startid) {
		
		Log.d("mensaje", intent.getExtras().getString("datos"));

		String[] info = intent.getExtras().getString("datos").split("[/]");
		Log.d("data1", info[0]);
		Log.d("data2", info[1]);
		Log.d("data3", info[2]);
		
		//This method  for HttpConnection  
	    try 
	    {
	    	//CrossSite scripting para logearnos a la pagina de de validación:
	        HttpPost request = new HttpPost("http://www.um.edu.ar/fi/validarLogin.php");
	        
	        List<NameValuePair>  nameValuePairs = new ArrayList<NameValuePair>(3);
	        nameValuePairs.add(new BasicNameValuePair("documento", info[0]));
	        nameValuePairs.add(new BasicNameValuePair("legajo", info[1]));
	        nameValuePairs.add(new BasicNameValuePair("passwd", info[2]));
	        request.setEntity(new UrlEncodedFormEntity( nameValuePairs));
	       
 
	        HttpResponse response = client.execute(request);
 
	        in = new BufferedReader
            (new InputStreamReader(response.getEntity().getContent()));
            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();
            String page = sb.toString();
			Log.d(TAG, page);
			
			int loginvalue=page.indexOf("<title>Noticias</title>");
			
	        Intent i = new Intent();
	        i.setAction("um.android.data");
	        i.putExtra("retornologin",loginvalue);
	        sendBroadcast(i);
 
	    } 
     catch(Exception e)	    {System.out.println("Exp="+e);
	    }
    
		
	}
	
}